package com.lw.leetcode.hash.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 2131. 连接两字母单词得到的最长回文串
 *
 * @author liw
 * @version 1.0
 * @date 2022/5/6 16:39
 */
public class LongestPalindrome {

    public int longestPalindrome(String[] words) {
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            map.merge(word, 1, (a, b) -> a + b);
        }
        int sum = 0;
        StringBuilder sb = new StringBuilder(2);
        boolean f = false;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            int count = entry.getValue();
            if (count == 0) {
                continue;
            }
            String k = entry.getKey();
            if (k.charAt(0) == k.charAt(1)) {
                if ((count & 1) == 0) {
                    sum += (count << 1);
                } else {
                    sum += ((count - 1) << 1);
                    f = true;
                }
                continue;
            }
            String key = sb.append(k).reverse().toString();
            Integer v = map.get(key);
            if (v != null && v > 0) {
                sum += (Math.min(v, count) << 2);
                map.put(k, 0);
                map.put(key, 0);
            }
            sb.setLength(0);
        }
        return f ? sum + 2 : sum;
    }

}
